package com.example.maxfinance;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


public class CompleteActivity extends Activity {
	
	private static final int REQUEST_CODE_DRIVER_LICENSE = 1;
	private static final int REQUEST_CODE_CAR_REGO_STICKER1 = 2;
	private static final int REQUEST_CODE_CAR_REGO_STICKER2 = 3;
	private static final int REQUEST_CODE_BANK_TRANSACTION = 4;
	
	public static final String DRIVER_LICENSE_TYPE = "Driver License";
	public static final String CAR_REGO1_TYPE = "Car Rego1";
	public static final String CAR_REGO2_TYPE = "Car Rego2";
	public static final String BANK_TRANSACTION_TYPE = "Bank Transaction";
	
//	private Bitmap bitmap;
	
//	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	Button btnDriverLicense;
	Button btnInfDriverLicense;
	ImageView imgDriverLicense;
	String strDriverLicensePath;
	Button btnUploadDriverLicense;
	
	Button btnCarRegoStiker1;
	Button btnInfCarRegoSticker1;
	ImageView imgCarRegoStiker1;
	String strCarRegoStickerPath1;
	Button btnUploadCarRegoSticker1;
	
	Button btnCarRegoStiker2;
	Button btnInfCarRegoSticker2;
	ImageView imgCarRegoStiker2;
	String strCarRegoStickerPath2;
	Button btnUploadCarRegoSticker2;
	
	Button btnBankTransaction;
	Button btnInfBankTransaction;
	ImageView imgInfBankTransaction;
	String strBankTransationPath;
	Button btnUploadBankTransaction;
	
	String strAppID;
	
//	Button btnSubmit;
	
//	boolean		m_isDriverLicense;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete);
        
        initWidget();
        initValue();
        initEvent();
    }
	 
     private void initWidget() {
    	 btnDriverLicense = (Button) findViewById(R.id.driver_license_button);
    	 btnInfDriverLicense = (Button) findViewById(R.id.inf_driver_license_button);
    	 imgDriverLicense = (ImageView) findViewById(R.id.driver_license_imageView);
    	 btnUploadDriverLicense = (Button) findViewById(R.id.driver_license_upload_button);
    	 
    	 btnCarRegoStiker1 = (Button) findViewById(R.id.car_rego_sticker_button1);
    	 btnInfCarRegoSticker1 = (Button) findViewById(R.id.inf_car_rego_sticker_button1);
    	 imgCarRegoStiker1 = (ImageView) findViewById(R.id.car_rego_sticker_imageView1);
    	 btnUploadCarRegoSticker1 = (Button) findViewById(R.id.car_rego_sticker_upload_button1);

    	 btnCarRegoStiker2 = (Button) findViewById(R.id.car_rego_sticker_button2);
    	 btnInfCarRegoSticker2 = (Button) findViewById(R.id.inf_car_rego_sticker_button2);
    	 imgCarRegoStiker2 = (ImageView) findViewById(R.id.car_rego_sticker_imageView2);
    	 btnUploadCarRegoSticker2 = (Button) findViewById(R.id.car_rego_sticker_upload_button2);

    	 btnBankTransaction = (Button) findViewById(R.id.contact_submit_button);
    	 btnInfBankTransaction = (Button) findViewById(R.id.inf_bank_transactions_button);
    	 imgInfBankTransaction = (ImageView) findViewById(R.id.bank_transactions_imageView);
    	 btnUploadBankTransaction = (Button) findViewById(R.id.bank_transactions_upload_button);
    	 
//    	 btnSubmit = (Button) findViewById(R.id.submit_button);
     }
     
     private void initValue() {
    	 
    	 strDriverLicensePath = null;
    	 strCarRegoStickerPath1 = null;
    	 strCarRegoStickerPath2 = null;
    	 strBankTransationPath = null;
    	 
    	 strAppID = GlobalData.personalInfo.strAppID;
//    	 strAppID = "438643";
//    	 m_isDriverLicense = false;
     }
     
     private void initEvent() {
    	 btnDriverLicense.setOnClickListener(new Button.OnClickListener() {

 			@Override
 			public void onClick(View v) {
 				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				try {
 					f = getPhotoFile(DRIVER_LICENSE_TYPE);
// 					strDriverLicensePath = f.getAbsolutePath();
 					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				} catch (IOException e) {
 					e.printStackTrace();
 					f = null;
// 					strDriverLicensePath = null;
 				}
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_DRIVER_LICENSE);
 			}
         });
    	 
    	 btnCarRegoStiker1.setOnClickListener(new Button.OnClickListener() {

 			@Override
 			public void onClick(View v) {
 				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				try {
 					f = getPhotoFile(CAR_REGO1_TYPE);
// 					strCarRegoStickerPath1 = f.getAbsolutePath();
 					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				} catch (IOException e) {
 					e.printStackTrace();
 					f = null;
// 					strCarRegoStickerPath1 = null;
 				}
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_CAR_REGO_STICKER1);
 			}
         });
    	 
    	 btnCarRegoStiker2.setOnClickListener(new Button.OnClickListener() {

 			@Override
 			public void onClick(View v) {
 				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				try {
 					f = getPhotoFile(CAR_REGO2_TYPE);
// 					strCarRegoStickerPath2 = f.getAbsolutePath();
 					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				} catch (IOException e) {
 					e.printStackTrace();
 					f = null;
// 					strCarRegoStickerPath2 = null;
 				}
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_CAR_REGO_STICKER2);
 			}
         });
    	 
    	 btnBankTransaction.setOnClickListener(new Button.OnClickListener() {

 			@Override
 			public void onClick(View v) {
 				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				try {
 					f = getPhotoFile(BANK_TRANSACTION_TYPE);
// 					strBankTransationPath = f.getAbsolutePath();
 					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				} catch (IOException e) {
 					e.printStackTrace();
 					f = null;
// 					strBankTransationPath = null;
 				}
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_BANK_TRANSACTION);
 			}
         });
    	 
//    	 btnSubmit.setOnClickListener(new Button.OnClickListener() {
//
//  			@Override
//  			public void onClick(View v) {
//  				
//  				
//	  			ArrayList<Uri> uris = new ArrayList<Uri>();
//	  			File file;
//  				Uri u;
//  				
//  				Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
//  				i.putExtra(android.content.Intent.EXTRA_EMAIL,
//  						new String[] { "victor@morganfinance.com.au" });
//				
//  				String strSubject;
//  				String strLastName = GlobalData.personalInfo.strSurname1;
//  				strLastName.toUpperCase();
//  				strSubject = strLastName + ", " + GlobalData.personalInfo.strFirstName1 + "'s document";
//
//  				i.putExtra(Intent.EXTRA_SUBJECT, strSubject);
//  				i.putExtra(Intent.EXTRA_TEXT, "From Mobile app - " + GlobalData.strScreenType);
//  	  			
//  				if (strDriverLicensePath != null) {
//  					file = new File(strDriverLicensePath);
//  	  				u = Uri.fromFile(file);
//  	  		        uris.add(u);	
//  				}
//  				
//  				if (strCarRegoStickerPath1 != null) {
//  	  		        file = new File(strCarRegoStickerPath1);
//  					u = Uri.fromFile(file);
//  			        uris.add(u);
//  				}
//  				
//  				if (strCarRegoStickerPath2 != null) {
//  			        file = new File(strCarRegoStickerPath2);
//  	  				u = Uri.fromFile(file);
//  	  		        uris.add(u);
//  				}
//  				
//  				if (strBankTransationPath != null) {
//  			        file = new File(strBankTransationPath);
//  	  				u = Uri.fromFile(file);
//  	  		        uris.add(u);
//  				}
//
//  				i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);  		        
//  				i.setType("text/plain");
//  				startActivity(Intent.createChooser(i, "E-mail"));	
//  				
//  			}
//         });
    	 
    	 btnInfDriverLicense.setOnClickListener(new Button.OnClickListener() {

  			@Override
  			public void onClick(View v) {
  		     	new AlertDialog.Builder(CompleteActivity.this)
  		        .setTitle("Information")
  		        .setMessage("Where can I get photo ID?\n" + 
  		        		"You can apply for a Photo card or Proof of Age card from the Road Authority if you currently do not have one.\n\n" +
  		        		"Must my ID be Australia issued?\n" +
  		        		"Yes, all driver licence and passport must be Australia issued.")
  		        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  		            public void onClick(DialogInterface dialog, int which) {
  		                // continue with delete
  		            }
  		         })
  		         .show();
  			}
    	 });
    	 
    	 btnUploadDriverLicense.setOnClickListener(new Button.OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				if (strDriverLicensePath == null) return;
  				
  				try {
  		         	new MyAsyncTask(CompleteActivity.this).execute("upload", strAppID, DRIVER_LICENSE_TYPE, strDriverLicensePath);
  		         } catch (Exception e) {
  		         	
  		         }
  			}
          });
    	 
    	 btnUploadCarRegoSticker1.setOnClickListener(new Button.OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				if (strCarRegoStickerPath1 == null) return;
  				new MyAsyncTask(CompleteActivity.this).execute("upload", strAppID, CAR_REGO1_TYPE, strCarRegoStickerPath1);
  			}
          });
    	 
    	 btnUploadCarRegoSticker2.setOnClickListener(new Button.OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				if (strCarRegoStickerPath2 == null) return;
  				new MyAsyncTask(CompleteActivity.this).execute("upload", strAppID, CAR_REGO2_TYPE, strCarRegoStickerPath2);
  			}
          });
    	 
    	 btnUploadBankTransaction.setOnClickListener(new Button.OnClickListener() {
    		
  			@Override
  			public void onClick(View v) {
  				if (strBankTransationPath == null) return;
  				new MyAsyncTask(CompleteActivity.this).execute("upload", strAppID, BANK_TRANSACTION_TYPE, strBankTransationPath);
  			}
         });
     }
     
     public void showGeneralAlert(String title, String message) {
     	new AlertDialog.Builder(CompleteActivity.this)
     	
         .setTitle(title)
         .setMessage(message)
         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) { 
                 // continue with delete
             }
          })
          .show();
     }
     
	private File getPhotoFile(String fileType) throws IOException {
	
		String filePath = Environment.getExternalStorageDirectory().getPath();
		
		String firstName = GlobalData.personalInfo.strFirstName1;
		String sureName = GlobalData.personalInfo.strSurname1;
		String birthday = GlobalData.personalInfo.strDOB;
		
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String currentDateandTime = sdf.format(c.getTime());
				
		String fileName = firstName + "_" + sureName + "_" + birthday + "_" + currentDateandTime + JPEG_FILE_SUFFIX;
		
		if (fileType == DRIVER_LICENSE_TYPE) {
			strDriverLicensePath = fileName;
		}
		if (fileType == CAR_REGO1_TYPE) {
			strCarRegoStickerPath1 = fileName;
		}
		if (fileType == CAR_REGO2_TYPE) {
			strCarRegoStickerPath2 = fileName;
		}
		if (fileType == BANK_TRANSACTION_TYPE) {
			strBankTransationPath = fileName;
		}
				
		File tempFile = new File(filePath, fileName);
		
		return tempFile;
	}
	
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {

			if (requestCode == REQUEST_CODE_DRIVER_LICENSE) {
		  		imgDriverLicense.setImageBitmap(getPicture(strDriverLicensePath));
 			}
			if (requestCode == REQUEST_CODE_CAR_REGO_STICKER1) {
				imgCarRegoStiker1.setImageBitmap(getPicture(strCarRegoStickerPath1));
 			}
			if (requestCode == REQUEST_CODE_CAR_REGO_STICKER2) {
				imgCarRegoStiker2.setImageBitmap(getPicture(strCarRegoStickerPath2));
 			}
			if (requestCode == REQUEST_CODE_BANK_TRANSACTION) {
				imgInfBankTransaction.setImageBitmap(getPicture(strBankTransationPath));
 			}
    	 }
		
		if (resultCode == RESULT_CANCELED) {
			strDriverLicensePath = null;
			strCarRegoStickerPath1 = null;
			strCarRegoStickerPath2 = null;
			strBankTransationPath = null;
		}
     }
     
     private Bitmap getPicture(String fileName) {
     	int targetW = 30;
  		int targetH = 50;

  		String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;

  		/* Get the size of the image */
  		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
  		bmOptions.inJustDecodeBounds = true;
  		BitmapFactory.decodeFile(filePath, bmOptions);
  		int photoW = bmOptions.outWidth;
  		int photoH = bmOptions.outHeight;
  		
  		/* Figure out which way needs to be reduced less */
  		int scaleFactor = 1;
  		if ((targetW > 0) || (targetH > 0)) {
  			scaleFactor = Math.min(photoW/targetW, photoH/targetH);
  		}

  		/* Set bitmap options to scale the image decode target */
  		bmOptions.inJustDecodeBounds = false;
  		bmOptions.inSampleSize = scaleFactor;
  		bmOptions.inPurgeable = true;

  		/* Decode the JPEG file into a Bitmap */
  		
  		Bitmap bitmap = BitmapFactory.decodeFile(filePath, bmOptions);
  		
  		/* Associate the Bitmap to the ImageView */
  		
  		Matrix matrix = new Matrix();
        matrix.postRotate(90);
//        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  		
//        m_isDriverLicense = true;
        
        return bitmap;
  		
     }
}